import mongoose from 'mongoose'
import config from '../config'
import fs from 'fs'
import { resolve } from 'path'

const r = path => resolve(__dirname,path) //将路径片段转成一个绝对路径
const models = r('../database/schema')
/**
 * 依次引入本地爬去好的json文件，插入数据库
 */
var areaJson = require('database/json/AreaDetail.json')
var areaHouseJson = require('database/json/AreaHouse.json')
var detailHouseJson = require('database/json/detailHouse.json')

/**
 * 依次引入schema
 */
fs.readdirSync(models) //读取文件
    .filter(file => ~file.search(/^[^\.].*js$/)) //筛选出后缀是js的文件
    .forEach(file => require(resolve(models,file))) 

export const database = app =>{
    mongoose.set('debug',true)
    mongoose.connect(config.db)
    mongoose.connection.on('disconnected', ()=>{
        mongoose.connect(config.db)
    })
    mongoose.connection.on('error', err =>{
        console.log(err)
    })
    mongoose.connection.on('open', async () =>{
        console.log('connected to MongoDb',config.db)
        /**
         * 杭州主城区数据入库
         */
        let area = mongoose.model('area')
        let areaDataBase = await area.find({}).exec()
        if (!areaDataBase.length) area.insertMany(areaJson)
        /**
         * 杭州主城区的房价数据入库
         */
        let areaHouse = mongoose.model('areaHouse')
        let areaHouseDataBase = await areaHouse.find({}).exec()
        if(!areaHouseDataBase.length) areaHouse.insertMany(areaHouseJson)

        /**
         * 杭州主城区里包括了分区的房价数据入库
         */
        let detailHouse = mongoose.model('detailHouse')
        let detailHouseDataBase = await detailHouse.find({}).exec()
        if(!detailHouseDataBase.length) detailHouse.insertMany(detailHouseJson)

    })
}